﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using Meqs.Entity.Views;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Credit_Teacher_Reprots_StudentEvalHistory : ContainerBasePage
{
    protected static int StuID
    {
        get
        {
            int id;
            if (int.TryParse(HttpContext.Current.Request["id"], out id))
                return id;
            return -1;
        }
    }

    protected static String StuCode
    {
        get
        {
            String code;
            code = HttpContext.Current.Request["code"];
            return code;
        }
    }

    protected static String StuName
    {
        get
        {
            String name;
            name = HttpUtility.UrlDecode(HttpContext.Current.Request["name"]);
            return name;
        }
    }

    private CauseFormula causeFormula;
    private CauseLevelTool causeLevelTool;

    private IList<SchoolInfo> schoolList = null;
    protected IList<CreditHistory> creditList = null;
    protected IList<StudentHistory> historyList = null;
    private IList<StudentMoralityScoreView> moralityList = null;
    private IList<StudentTestScoreView> testSocreList = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            Bind(true);
        }
    }

    private void Bind(bool isCounting)
    {
        // 获取学校性质
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", SchoolMark);
        schoolList = Container<ISchoolInfoLogic>.Instance.FindAll(ht);
        if (schoolList == null || schoolList.Count < 1)
            return;

        // 学生历史学分
        creditList = Container<IStuCausePersonCatchLogic>.Instance.GetStudentHistoryReport(SchoolMark, StuID);
        //ListSort<CreditHistory> sort = new ListSort<CreditHistory>(creditList, "CauseID", false);
        //creditList = sort.Sort();

        ht = new Hashtable();
        ht.Add("StudentID", StuID);
        historyList = Container<IStudentHistoryLogic>.Instance.FindAll(ht);

        // 德育分数
        moralityList = Container<IMoralityPersonCatchLogic>.Instance.GetMoralityHistoryReport(SchoolMark, StuID);

        // 期末成绩
        testSocreList = Container<IClassResultExamListLogic>.Instance.FindTestScoreHistoryByStuID(SchoolMark, StuID);

        
        causeLevelTool = new CauseLevelTool(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, SchoolMark);


        CreateTable(schoolList[0], creditList, moralityList, testSocreList, historyList,isCounting);
    }

    private bool HasThisCourseInGrade(int grade, int courseID)
    {
        Hashtable ht = new Hashtable();
        ht.Add("CourseID", courseID);
        ht.Add("SchoolMark", SchoolMark);
        IList<CouseGradeInfo> cgList = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);
        bool gradehascourse = false;
        foreach (CouseGradeInfo info in cgList)
        {
            if (grade == info.Grade)
            {
                gradehascourse = true;
                break;
            }
        }
        return gradehascourse;
    }

    /// <summary>
    /// 构造报表
    /// </summary>
    /// <param name="schoolInfo"></param>
    /// <param name="creditList"></param>
    /// <param name="moralityList"></param>
    /// <param name="testSocreList"></param>
    /// <param name="historyList"></param>
    /// <param name="isCounting">综合统计是否包括德育</param>
    private void CreateTable(SchoolInfo schoolInfo, IList<CreditHistory> creditList,
                            IList<StudentMoralityScoreView> moralityList,IList<StudentTestScoreView> testSocreList,
                            IList<StudentHistory> historyList, bool isCounting)
    {
        Dictionary<int, String> gradeList = CreateGradeCellTool(schoolInfo.SchoolOpt);
        
        // 构造表头
        CreateTableHeader(gradeList);

        // 年级总成绩
        Dictionary<int, double> sumscoreList = new Dictionary<int, double>();
        #region 构造内容
        int rows = 0;
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        Dictionary<int, double> scoreList = new Dictionary<int, double>();
        Dictionary<int, double> testList = new Dictionary<int, double>();

        int oldCauseID = -1;
        foreach (CreditHistory history in creditList)
        {
            if (oldCauseID != history.CauseID)
            { // 新科目行
                if (oldCauseID != -1)
                { // 不是第一行 
                    CreateContextRow(gradeList, row, scoreList, testList, ref sumscoreList, historyList, oldCauseID);
                }
                row = new TableRow();
                // 学科名
                cell = new TableCell();
                cell.CssClass = "FixedCol";
                cell.Text = history.CauseName;
                row.Cells.Add(cell);
                // 年级学分
                scoreList = new Dictionary<int, double>();

                testList = new Dictionary<int, double>();
                rows++;
            }
            if (!history.Grade.HasValue || !history.Score.HasValue || !history.Term.HasValue)
            {
                oldCauseID = history.CauseID;
                continue;
            }

            int grade;
            // 下学期 = 年级 + 100
            if (history.Term.Value == 2)
                grade = history.Grade.Value + 100;
            else
                grade = history.Grade.Value;

            double score = history.Score.Value;
            if (!scoreList.ContainsKey(grade))
                scoreList.Add(grade, score);
            else
                scoreList[grade] += score;

            // 期末成绩
            foreach (StudentTestScoreView view in testSocreList)
            {
                if (view.CauseID == history.CauseID && view.SchoolYear == history.SchoolYear &&
                    view.Term == history.Term && !testList.ContainsKey(grade))
                {
                    testList.Add(grade, view.Score);
                    break;
                }
            }
            oldCauseID = history.CauseID;
        }

        CreateContextRow(gradeList, row, scoreList, testList, ref sumscoreList, historyList,oldCauseID);
        #endregion

        #region 德育行


        double sumCauseScoret = 0;
        int iit = 0;
        double stt = 0;
        if (isCounting)//统计德语行
        {
            row = new TableRow();

            // 学科名
            cell = new TableCell();
            cell.Text = "德育表现";
            cell.CssClass = "FixedCol";
            row.Cells.Add(cell);

            scoreList = new Dictionary<int, double>();

            Dictionary<int, double> moralityScore = new Dictionary<int, double>();
            foreach (StudentMoralityScoreView view in moralityList)
            {
                int grade = 0;
                if (view.Term == 2)
                    grade = view.Grade + 100;
                else
                    grade = view.Grade;

                if (!moralityScore.ContainsKey(grade))
                    moralityScore.Add(grade, getMortalScore(moralityList, view.Grade, view.Term));


            }

        
            foreach (KeyValuePair<int, string> pair in gradeList)
            {
                int zz = 1;
                for (int x = pair.Key; x < 200; x += 100)
                {
                    double morScore = 0;
                    if (moralityScore.ContainsKey(x))
                        morScore = moralityScore[x];
                    cell = new TableCell();
                    double t = causeFormula.GetMoralScore(morScore);
                    t = t > 100 ? 100 : t;
                    if (HasThisGrade(historyList, pair.Key, zz) && t>0)
                        cell.Text = Math.Round(t, 2).ToString();
                    else
                        cell.Text = "";
                    row.Cells.Add(cell);

                    //等级
                    cell = new TableCell();
                    if (HasThisGrade(historyList, pair.Key, zz) && t > 0)
                        cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, t);
                    else
                        cell.Text = "";
                    row.Cells.Add(cell);

                    // 各科综合分数计算
                    if (HasThisGrade(historyList, pair.Key, zz))
                    {
                        if (!sumscoreList.ContainsKey(x))
                            sumscoreList.Add(x, t);
                        else
                            sumscoreList[x] += t;
                        sumCauseScoret += t;
                        if (t > 0)
                            iit++;
                    }
                    zz++;
                }
            }

            cell = new TableCell();
            stt = sumCauseScoret / iit;
            cell.Text = Math.Round(stt, 2).ToString();
            row.Cells.Add(cell);
            cell = new TableCell();
            cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear,SchoolCommon.Sch_SchoolInfo.SchoolTerm, stt);
        
            row.Cells.Add(cell);
            rows++;
            tbResult.Rows.Add(row);
        }
        #endregion

        #region 各科综合评价行
        row = new TableRow();
        // 学科名
        cell = new TableCell();
        cell.Text = "各科综合评价";
        cell.CssClass = "FixedCol";
        row.Cells.Add(cell);

        sumCauseScoret = 0;
        iit = 0;
        foreach (KeyValuePair<int, string> pair in gradeList)
        {
            int zz = 1;
            for (int x = pair.Key; x < 200; x += 100)
            {
                double morScore = 0;
                if (sumscoreList.ContainsKey(x))
                    morScore = sumscoreList[x];

                Hashtable ht = new Hashtable();
                ht.Add("Grade", pair.Key);
                ht.Add("SchoolMark", SchoolMark);
                IList<CouseGradeInfo> cgList = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);

                cell = new TableCell();
                double t = 0;
                if (cgList.Count > 0)
                    t = morScore / (cgList.Count);
                if (HasThisGrade(historyList, pair.Key, zz))
                    cell.Text = Math.Round(t, 2).ToString();
                else
                    cell.Text = "";
                row.Cells.Add(cell);

                //等级
                cell = new TableCell();
                if (HasThisGrade(historyList, pair.Key, zz))
                    cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, t);
                else
                    cell.Text = "";
                row.Cells.Add(cell);


                sumCauseScoret += t;
                
                if (HasThisGrade(historyList, pair.Key, zz))
                    iit++;
               
                zz++;
            }

        }
    if (!isCounting)//如不统计德语行 则减去分母
    {
        iit--;
    }
    cell = new TableCell();
        stt = sumCauseScoret / iit;
        cell.Text = Math.Round(stt, 2).ToString();
        row.Cells.Add(cell);
        cell = new TableCell();
        cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear,SchoolCommon.Sch_SchoolInfo.SchoolTerm, stt);
        row.Cells.Add(cell);

        tbResult.Rows.Add(row);
        #endregion
    }

    private double getMortalScore(IList<StudentMoralityScoreView> moralityList,int grade,int sterm)
    {
        double score = 0;
        int num = 0;
        foreach (StudentMoralityScoreView view in moralityList)
        {
            if (grade == view.Grade && view.Term == sterm) 
            {
                score += view.Score;
                num++;
            }
        }
        if (num > 0)
        {
            score = Math.Round(score / num, 2);
            return score;
        }
        return 0;
    }
    private void CreateContextRow(Dictionary<int, String> gradeList, TableRow row,
                Dictionary<int, double> scoreList, Dictionary<int, double> testList,
                ref Dictionary<int, double> sumscoreList, IList<StudentHistory> historyList, int courseID)
    {
        TableCell cell;
        double sumCauseScore = 0;
        int ii = 0;

        foreach (KeyValuePair<int, string> pair in gradeList)
        {
            if (HasThisCourseInGrade(pair.Key, courseID) || testList.ContainsKey(pair.Key))
            {
                causeFormula = new CauseFormula(SchoolMark,courseID);
                // 上学期
                //分数
                double testScore = 0;
                double causeScore = 0;
                if (testList.ContainsKey(pair.Key))
                    testScore = testList[pair.Key];
                if (scoreList.ContainsKey(pair.Key))
                    causeScore = scoreList[pair.Key];
                cell = new TableCell();
                double t = causeFormula.GetCauseScore(causeScore, testScore,courseID);
                if (HasThisGrade(historyList, pair.Key, 1))
                    cell.Text = Math.Round((t>100?100:t), 2).ToString();
                else
                    cell.Text = "";
                row.Cells.Add(cell);

                //等级
                cell = new TableCell();
                if (HasThisGrade(historyList, pair.Key, 1))
                    cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, (t > 100 ? 100 : t));
                else
                    cell.Text = "";

                row.Cells.Add(cell);

                // 各科综合分数计算
                if (HasThisGrade(historyList, pair.Key, 1))
                {
                    if (!sumscoreList.ContainsKey(pair.Key))
                        sumscoreList.Add(pair.Key, t);
                    else
                        sumscoreList[pair.Key] += t;
                    sumCauseScore += t;
                    ii++;
                }

                // 下学期
                //分数
                testScore = 0;
                causeScore = 0;
                if (testList.ContainsKey(pair.Key + 100))
                    testScore = testList[pair.Key + 100];
                if (scoreList.ContainsKey(pair.Key + 100))
                    causeScore = scoreList[pair.Key + 100];
                cell = new TableCell();
                t = causeFormula.GetCauseScore(causeScore, testScore,courseID);
                if (HasThisGrade(historyList, pair.Key, 2))
                    cell.Text = Math.Round(t, 2).ToString();
                else
                    cell.Text = "";
                row.Cells.Add(cell);

                //等级
                cell = new TableCell();
                if (HasThisGrade(historyList, pair.Key, 2))
                    cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, t);
                else
                    cell.Text = "";
                row.Cells.Add(cell);

                // 各科综合分数计算
                if (HasThisGrade(historyList, pair.Key, 2))
                {
                    if (!sumscoreList.ContainsKey(pair.Key + 100))
                        sumscoreList.Add(pair.Key + 100, t);
                    else
                        sumscoreList[pair.Key + 100] += t;

                    sumCauseScore += t;
                    ii++;
                }
            }
            else
            {
                for (int z = 0; z < 4; z++)
                {
                    cell = new TableCell();
                    cell.Text = "";
                    row.Cells.Add(cell);
                }
                tbResult.Rows.Add(row);
            }
        }
        cell = new TableCell();
        double st = sumCauseScore / ii;
        if (!Double.IsNaN(st))
            cell.Text = Math.Round(st, 2).ToString();
        else
            cell.Text = "";
        row.Cells.Add(cell);
        cell = new TableCell();
        if (!Double.IsNaN(st))
            cell.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear,SchoolCommon.Sch_SchoolInfo.SchoolTerm, st);
        else
            cell.Text = "";
        row.Cells.Add(cell);

        tbResult.Rows.Add(row);
    }

    private bool HasThisGrade(IList<StudentHistory> historyList, int grade, int term)
    {
        foreach (StudentHistory history in historyList)
        {
            if (history.Grade == grade && term == history.Term)
                return true;
        }
        return false;
    }

    /// <summary>
    /// 创建表头
    /// </summary>
    private void CreateTableHeader(Dictionary<int, String> gradeList)
    {
        int width = 0;
        TableRow hrow = new TableRow();
        TableCell hcell = new TableCell();
        TableRow secRow = new TableRow();
        TableRow thrRow = new TableRow();
        hcell.Text = "科目";
        hcell.CssClass = "FixedRowCol";
        hcell.Style[HtmlTextWriterStyle.Width] = "100px";
        width += 100;
        hcell.RowSpan = 3;
        hrow.Cells.Add(hcell);

        //构造年级
        foreach (KeyValuePair<int, string> pair in gradeList)
        {
            hcell = new TableCell();
            hcell.Text = pair.Value;
            hcell.CssClass = "FixedRow";
            hcell.Style[HtmlTextWriterStyle.Width] = "200px";

            hcell.ColumnSpan = 4;
            hrow.Cells.Add(hcell);

            hcell = new TableCell();
            hcell.Text = "上学期";
            hcell.CssClass = "FixedRow";
            hcell.Style[HtmlTextWriterStyle.Width] = "100px";

            hcell.ColumnSpan = 2;
            secRow.Cells.Add(hcell);

            hcell = new TableCell();
            hcell.Text = "下学期";
            hcell.CssClass = "FixedRow";
            hcell.Style[HtmlTextWriterStyle.Width] = "100px";

            hcell.ColumnSpan = 2;
            secRow.Cells.Add(hcell);

            for (int i = 0; i < 4; i++)
            {
                hcell = new TableCell();
                if (i % 2 == 0)
                    hcell.Text = "学分";
                else
                    hcell.Text = "等级";
                hcell.CssClass = "FixedRow";
                hcell.Style[HtmlTextWriterStyle.Width] = "50px";
                width += 50;
                thrRow.Cells.Add(hcell);
            }
        }

        hcell = new TableCell();
        hcell.Text = "毕业学分";
        hcell.CssClass = "FixedRow";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.RowSpan = 3;
        hrow.Cells.Add(hcell);

        hcell = new TableCell();
        hcell.Text = "毕业评定等级";
        hcell.CssClass = "FixedRow";
        hcell.Style[HtmlTextWriterStyle.Width] = "120px";
        width += 120;
        hcell.RowSpan = 3;
        hrow.Cells.Add(hcell);

        tbResult.Rows.Add(hrow);
        tbResult.Rows.Add(secRow);
        tbResult.Rows.Add(thrRow);
        hrow.Style["background-color"] = "#D4F1F9";
        secRow.Style["background-color"] = "#D4F1F9";
        thrRow.Style["background-color"] = "#D4F1F9";
        tbResult.Style[HtmlTextWriterStyle.Width] = String.Format("{0}px", width);
    }

    /// <summary>
    /// 获取年级键值对
    /// </summary>
    private Dictionary<int, String> CreateGradeCellTool(int schoolType)
    {
        Dictionary<int, String> gradeList = new Dictionary<int, String>();
        switch (schoolType)
        {
            case 1:
                gradeList.Add(1, "一年级");
                gradeList.Add(2, "二年级");
                gradeList.Add(3, "三年级");
                gradeList.Add(4, "四年级");
                gradeList.Add(5, "五年级");
                gradeList.Add(6, "六年级");
                break;
            case 2:
                gradeList.Add(7, "初一");
                gradeList.Add(8, "初二");
                gradeList.Add(9, "初三");
                break;
            case 3:
                gradeList.Add(10, "高一");
                gradeList.Add(11, "高二");
                gradeList.Add(12, "高三");
                break;
            case 4:
                gradeList.Add(1, "一年级");
                gradeList.Add(2, "二年级");
                gradeList.Add(3, "三年级");
                gradeList.Add(4, "四年级");
                gradeList.Add(5, "五年级");
                gradeList.Add(6, "六年级");
                gradeList.Add(7, "初一");
                gradeList.Add(8, "初二");
                gradeList.Add(9, "初三");
                break;
            case 5:
                gradeList.Add(7, "初一");
                gradeList.Add(8, "初二");
                gradeList.Add(9, "初三");
                gradeList.Add(10, "高一");
                gradeList.Add(11, "高二");
                gradeList.Add(12, "高三");
                break;
        }

        return gradeList;

    }

    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells, int causeID)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "download\\" + StuCode + "_profile.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, StuCode + "学生成长档案", 2, 0, cells);
        return "";
    }
    protected void btnBind_Click(object sender, EventArgs e)
    {
        string s = txtIsCount.Text;
        if(!string.IsNullOrEmpty(s))
        {
            if(s == "1")
            {
                //计算
                Bind(true);
            }
            else
            {
                //不计算    
                Bind(false);
            }
        }
    }
}

